import { PrismaService } from '@/prisma/prisma.service';
import { Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';

@Injectable()
export class ArticleService {
  constructor(private prisma: PrismaService) {}
  create(createArticleDto: CreateArticleDto) {
    return this.prisma.article.create({
      data: {
        title: createArticleDto.title,
        content: createArticleDto.content,
        categoryId: +createArticleDto.categoryId,
      },
    });
  }

  /**
   * 查询全部文章-分页查询
   * @param currentPage 当前页
   * @param pageSize 每页多少条
   * @returns
   */
  async findAll(currentPage = 1, pageSize: number) {
    const article = await this.prisma.article.findMany({
      skip: (currentPage - 1) * pageSize, // 起始页
      take: Number(pageSize), // 每页多台 这里需要转换为数值类型 也可以使用 +pageSize隐式转换
    });

    const total = await this.prisma.article.count();
    return {
      data: article,
      meta: {
        total,
        currentPage,
        pageSize,
      },
    };
  }

  findOne(id: number) {
    return this.prisma.article.findFirst({
      where: {
        id,
      },
    });
  }

  update(id: number, updateArticleDto: UpdateArticleDto) {
    return this.prisma.article.update({
      where: { id },
      data: {
        title: updateArticleDto.title,
        content: updateArticleDto.content,
        categoryId: +updateArticleDto.categoryId,
      },
    });
  }

  remove(id: number) {
    return this.prisma.article.delete({
      where: {
        id,
      },
    });
  }
}
